import React, { useState, useEffect } from 'react';
import { Modal, Card, Radio, Checkbox, Input, Button, Space, Divider, message, Progress } from 'antd';
import { ClockCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import styled from 'styled-components';

const { TextArea } = Input;

interface Question {
  id: string;
  question: string;
  type: "single" | "multiple" | "text";
  options?: string[];
  correctAnswer?: string | string[];
  studentAnswer?: string | string[];
  isCorrect?: boolean;
  score?: number;
  fullScore?: number;
  explanation?: string;
}

interface Homework {
  id: string;
  title: string;
  course: string;
  teacher: string;
  description: string;
  deadline: string;
  status: "未提交" | "已提交" | "已批改" | "已过期";
  type: "file" | "quiz";
  score?: number;
  fullScore?: number;
  submittedAt?: string;
  gradedAt?: string;
  feedback?: string;
  attachments?: string[];
  submittedFiles?: string[];
  questions?: Question[];
  hasAIExplanation?: boolean;
}

interface QuizSubmissionModalProps {
  visible: boolean;
  homework: Homework | null;
  onCancel: () => void;
  onSubmit: (homeworkId: string, answers: Record<string, string | string[]>) => void;
}

const StyledModal = styled(Modal)`
  .ant-modal-content {
    max-height: 80vh;
    overflow-y: auto;
  }
`;

const QuestionCard = styled(Card)`
  margin-bottom: 16px;
  border: 1px solid #d9d9d9;
  
  .ant-card-head {
    background-color: #fafafa;
    border-bottom: 1px solid #d9d9d9;
  }
`;

const OptionItem = styled.div`
  margin: 8px 0;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #1890ff;
    background-color: #f0f8ff;
  }
  
  &.selected {
    border-color: #1890ff;
    background-color: #e6f7ff;
  }
`;

const QuizSubmissionModal: React.FC<QuizSubmissionModalProps> = ({
  visible,
  homework,
  onCancel,
  onSubmit
}) => {
  const [answers, setAnswers] = useState<Record<string, string | string[]>>({});
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [timeLeft, setTimeLeft] = useState(0);

  useEffect(() => {
    if (visible && homework) {
      // 初始化答案
      const initialAnswers: Record<string, string | string[]> = {};
      homework.questions?.forEach(q => {
        if (q.type === 'multiple') {
          initialAnswers[q.id] = [];
        } else {
          initialAnswers[q.id] = '';
        }
      });
      setAnswers(initialAnswers);
      setCurrentQuestion(0);
      
      // 设置倒计时（模拟30分钟）
      setTimeLeft(30 * 60);
    }
  }, [visible, homework]);

  useEffect(() => {
    if (timeLeft > 0) {
      const timer = setTimeout(() => {
        setTimeLeft(timeLeft - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (timeLeft === 0 && visible) {
      message.warning('时间到！系统将自动提交答案');
      handleSubmit();
    }
  }, [timeLeft, visible]);

  const handleAnswerChange = (questionId: string, value: string | string[]) => {
    setAnswers(prev => ({
      ...prev,
      [questionId]: value
    }));
  };

  const handleSingleChoice = (questionId: string, option: string) => {
    handleAnswerChange(questionId, option);
  };

  const handleMultipleChoice = (questionId: string, option: string, checked: boolean) => {
    const currentAnswers = (answers[questionId] as string[]) || [];
    if (checked) {
      handleAnswerChange(questionId, [...currentAnswers, option]);
    } else {
      handleAnswerChange(questionId, currentAnswers.filter(a => a !== option));
    }
  };

  const handleTextAnswer = (questionId: string, value: string) => {
    handleAnswerChange(questionId, value);
  };

  const handleSubmit = () => {
    // 检查是否所有题目都已回答
    const unansweredQuestions = homework?.questions?.filter(q => {
      const answer = answers[q.id];
      if (q.type === 'multiple') {
        return !Array.isArray(answer) || answer.length === 0;
      } else {
        return !answer || answer === '';
      }
    });

    if (unansweredQuestions && unansweredQuestions.length > 0) {
      message.warning(`还有 ${unansweredQuestions.length} 道题目未完成，确定要提交吗？`);
    }

    if (homework) {
      onSubmit(homework.id, answers);
    }
  };

  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  const getProgressPercentage = () => {
    if (!homework?.questions) return 0;
    const answeredCount = homework.questions.filter(q => {
      const answer = answers[q.id];
      if (q.type === 'multiple') {
        return Array.isArray(answer) && answer.length > 0;
      } else {
        return answer && answer !== '';
      }
    }).length;
    return (answeredCount / homework.questions.length) * 100;
  };

  if (!homework || !homework.questions) {
    return null;
  }

  const currentQ = homework.questions[currentQuestion];

  return (
    <StyledModal
      title={
        <div>
          <h3>{homework.title}</h3>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>选择题作业</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <ClockCircleOutlined style={{ color: timeLeft < 300 ? '#ff4d4f' : '#1890ff' }} />
              <span style={{ color: timeLeft < 300 ? '#ff4d4f' : '#1890ff', fontWeight: 'bold' }}>
                {formatTime(timeLeft)}
              </span>
            </div>
          </div>
        </div>
      }
      visible={visible}
      onCancel={onCancel}
      width={800}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="prev" 
          disabled={currentQuestion === 0}
          onClick={() => setCurrentQuestion(prev => Math.max(0, prev - 1))}
        >
          上一题
        </Button>,
        <Button key="next" 
          type="primary"
          disabled={currentQuestion === homework.questions!.length - 1}
          onClick={() => setCurrentQuestion(prev => Math.min(homework.questions!.length - 1, prev + 1))}
        >
          下一题
        </Button>,
        <Button key="submit" 
          type="primary" 
          danger
          onClick={handleSubmit}
        >
          提交答案
        </Button>
      ]}
    >
      <div style={{ marginBottom: 16 }}>
        <Progress 
          percent={getProgressPercentage()} 
          status="active"
          format={percent => `${Math.round(percent || 0)}%`}
        />
        <div style={{ textAlign: 'center', marginTop: 8 }}>
          第 {currentQuestion + 1} 题 / 共 {homework.questions.length} 题
        </div>
      </div>

      <QuestionCard
        title={`第 ${currentQuestion + 1} 题`}
        extra={
          <span style={{ color: currentQ.type === 'single' ? '#1890ff' : currentQ.type === 'multiple' ? '#52c41a' : '#fa8c16' }}>
            {currentQ.type === 'single' ? '单选题' : currentQ.type === 'multiple' ? '多选题' : '问答题'}
          </span>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <h4>{currentQ.question}</h4>
        </div>

        {currentQ.type === 'single' && currentQ.options && (
          <Radio.Group 
            value={answers[currentQ.id] as string} 
            onChange={(e) => handleSingleChoice(currentQ.id, e.target.value)}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              {currentQ.options.map((option, index) => (
                <OptionItem
                  key={index}
                  className={answers[currentQ.id] === option ? 'selected' : ''}
                  onClick={() => handleSingleChoice(currentQ.id, option)}
                >
                  <Radio value={option}>{option}</Radio>
                </OptionItem>
              ))}
            </Space>
          </Radio.Group>
        )}

        {currentQ.type === 'multiple' && currentQ.options && (
          <Checkbox.Group 
            value={answers[currentQ.id] as string[]} 
            onChange={(values) => handleAnswerChange(currentQ.id, values as string[])}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              {currentQ.options.map((option, index) => (
                <OptionItem
                  key={index}
                  className={(answers[currentQ.id] as string[])?.includes(option) ? 'selected' : ''}
                  onClick={() => handleMultipleChoice(currentQ.id, option, !(answers[currentQ.id] as string[])?.includes(option))}
                >
                  <Checkbox value={option}>{option}</Checkbox>
                </OptionItem>
              ))}
            </Space>
          </Checkbox.Group>
        )}

        {currentQ.type === 'text' && (
          <TextArea
            rows={6}
            placeholder="请输入您的答案..."
            value={answers[currentQ.id] as string}
            onChange={(e) => handleTextAnswer(currentQ.id, e.target.value)}
            showCount
            maxLength={500}
          />
        )}
      </QuestionCard>

      <div style={{ textAlign: 'center', marginTop: 16 }}>
        <Space>
          {homework.questions.map((_, index) => (
            <Button
              key={index}
              type={index === currentQuestion ? 'primary' : 'default'}
              size="small"
              onClick={() => setCurrentQuestion(index)}
            >
              {index + 1}
            </Button>
          ))}
        </Space>
      </div>
    </StyledModal>
  );
};

export default QuizSubmissionModal; 